package cqu.zhaiyixin20215521.huarondao.slice.huarondaoPlay;

import cqu.zhaiyixin20215521.huarondao.slice.huarondaoPlay.HuaRonDao;

import java.util.Random;

//随机生成一步移动
public class HuaRonDaoRandom {
    private final HuaRonDao huaRonDao;
    private int spaceRow; //空格所在行
    private int spaceCol; //空格所在列
    public int direction; //需要移动块的移动方向
    public int pieceRow; //需要移动的块所在的行
    public int pieceCol; //需要移动的块所在的列
    private final Random random;
    private final int[] directions = {HuaRonDao.UP, HuaRonDao.DOWN, HuaRonDao.LEFT, HuaRonDao.RIGHT};
    private int lastPace = -1; //上一步的方向，避免来回踱步显得很傻

    public HuaRonDaoRandom(HuaRonDao huaRonDao) {
        this.huaRonDao = huaRonDao;
        this.random = new Random(System.currentTimeMillis());
        update();
    }

    public void update() {
        //找空格所在的位置
        for(int i = 0; i < huaRonDao.rowNum; ++i) {
            for(int j = 0; j < huaRonDao.colNum; ++j) {
                if(huaRonDao.get(i, j) == huaRonDao.rowNum * huaRonDao.colNum - 1) {
                    spaceRow = i;
                    spaceCol = j;
                    break;
                }
            }
        }
        //随机生成一次移动
        boolean valid;
        do {
            direction = directions[random.nextInt(4)];
            switch (direction) {
                case HuaRonDao.UP:
                    pieceRow = spaceRow + 1;
                    pieceCol = spaceCol;
                    valid = pieceRow < huaRonDao.rowNum && lastPace != HuaRonDao.DOWN;
                    break;
                case HuaRonDao.DOWN:
                    pieceRow = spaceRow - 1;
                    pieceCol = spaceCol;
                    valid = 0 <= pieceRow && lastPace != HuaRonDao.UP;
                    break;
                case HuaRonDao.LEFT:
                    pieceRow = spaceRow;
                    pieceCol = spaceCol + 1;
                    valid = pieceCol < huaRonDao.colNum && lastPace != HuaRonDao.RIGHT;
                    break;
                case HuaRonDao.RIGHT:
                    pieceRow = spaceRow;
                    pieceCol = spaceCol - 1;
                    valid = 0 <= pieceCol && lastPace != HuaRonDao.LEFT;
                    break;
                default:
                    valid = false;
            }
        } while (!valid);
        lastPace = direction;
    }
}